package com.easy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lxk on 2019/6/16.
 */
public class Solution811 {

    private void parseAndCount(String str,Map<String,Integer> domainCount){
        String[] kvs = str.split(" ");
        String[] strs = kvs[1].split("\\.");
        for(int i = 0;i < strs.length; i++){
            StringBuffer sb = new StringBuffer();
            for(int k = i;k < strs.length; k++){
                if(k==strs.length-1){
                    sb.append(strs[k]);
                }else{
                    sb.append(strs[k] + ".");
                }
            }
            String domain = sb.toString();
            if(domainCount.keySet().contains(domain)){
                domainCount.put(domain,domainCount.get(domain) + Integer.parseInt(kvs[0]));
            }else{
                domainCount.put(domain,Integer.parseInt(kvs[0]));
            }
        }
    }

    public List<String> subdomainVisits(String[] cpdomains) {
        List<String> res = new ArrayList<>();
        if(cpdomains==null){
            return res;
        }
        Map<String,Integer> domainCount = new HashMap<>();
        for(String val : cpdomains){
            parseAndCount(val,domainCount);
        }
        for(Map.Entry<String,Integer> entry : domainCount.entrySet()){
            res.add(entry.getValue() + " " + entry.getKey());
        }
        return res;
    }


    public static void main(String[] args) {
        String[] arr = {"9001 discuss.leetcode.com"};
        Solution811 solution811 = new Solution811();
        solution811.subdomainVisits(arr);
    }

}
